package cn.shop.merchant.service;

import cn.shop.merchant.mapper.media.NewsMapper;
import cn.shop.merchant.model.media.News;
import cn.shop.utils.PageUtil;
import cn.shop.utils.Putif;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author : 李一涵
 * @date : Created in 2021-11-4 10:00
 * @description : 新闻service
 */
@Service
public class NewsService extends BaseServiceImpl<NewsMapper, News> {

    /**
     * 获取新闻列表
     *
     * @param uid 商户编号
     * @param current 第几页
     * @param size 当前记录数
     * @param title 标题
     * @param order 排序
     */
    public Map<String, Object> list(long uid, int current, int size, String title, int order) {
        Page<News> page = Page.of(current, size);
        LambdaQueryWrapper<News> query = Wrappers.<News>lambdaQuery()
                .eq(News::getUid, uid)
                .like(notNull.test(title), News::getTitle, title)
                .orderBy(true, isAsc.test(order), News::getId);
        page = page(page, query);

        return PageUtil.formatPage(page, this::format);
    }

    /**
     * 更新新闻信息
     *
     * @param news 新闻
     * @param uid 商户编号
     */
    public boolean update(News news, long uid) {
        return update(news, Wrappers.<News>lambdaUpdate()
                .eq(News::getId, news.getId())
                .eq(News::getUid, uid));
    }

    /**
     * 删除新闻
     *
     * @param ids 编号，多个用逗号隔开
     * @param uid 商户编号
     */
    public boolean delete(long[] ids, long uid) {
        return SqlHelper.retBool(getBaseMapper().batchDeleteWithFill(new News(), Wrappers.<News>lambdaQuery()
                .in(News::getId, Arrays.stream(ids).boxed().collect(Collectors.toList()))
                .eq(News::getUid, uid)));
    }

    /**
     * 获取新闻信息
     *
     * @param id 编号
     * @param uid 商户编号
     */
    public Map<String, Object> info(long id, long uid) {
        News news = getOne(Wrappers.<News>lambdaQuery()
                .eq(News::getId, id).eq(News::getUid, uid));
        return format(news);
    }

    /**
     * 格式化新闻
     *
     * @param news 新闻
     */
    private Map<String, Object> format(News news) {
        if (news == null) {
            return Collections.emptyMap();
        }
        return Putif.start()
                .anyway("id", news.getId())
                .anyway("title", news.getTitle())
                .anyway("author", news.getAuthor())
                .anyway("source", news.getSource())
                .anyway("content", news.getContent())
                .anyway("creatTime", news.getCreateTime())
                .get();
    }

}
